// 接口地址
const baseUrl = 'http://localhost:8080/api'

/**
 * get 请求
 * @param {String} url Request 请求地址
 * @param {Object} data 请求参数
 * @returns {Promise}
 */
const get = (url = '', data = {}) => {
	return ajax(url, data, 'get');
}

/**
 * post 请求
 * @param {String} url Request 请求地址
 * @param {Object} data 请求参数
 * @returns {Promise}
 */
const post = (url = '', data = {}) => {
	return ajax(url, data, 'post');
}

/**
 * put 请求
 * @param {String} url Request 请求地址
 * @param {Object} data 请求参数
 * @returns {Promise}
 */
const put = (url = '', data = {}) => {
	return ajax(url, data, 'put');
}

/**
 * delete 请求
 * @param {String} url Request 请求地址
 * @param {Object} data 请求参数
 * @returns {Promise}
 */
const del = (url = '', data = {}) => {
	return ajax(url, data, 'delete');
}

/**
 * 综合请求
 * @param {String} url Request 请求地址
 * @param {Object} data 请求参数
 * @param {String} method post/get
 * @returns {Promise<Object>}
 */
const ajax = async (url = '', data = {}, method = 'get') => {

	let header = {
		'Authorization': 'Bearer ' + (uni.getStorageSync('token') || ''),
		'Content-Type': 'application/json'
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			data: {
				...data,
			},
			header: header,
			method: method,
			dataType: 'json',
			success: async (res) => { // 请求成功处理
				switch (res.data.code) {
					case 401:
						uni.showToast({
							icon: 'none',
							title: '登录过期或未登录'
						});
						let roww = res;
						setTimeout(() => resolve(roww), 1400)
						break;
					case 404:
						uni.showToast({
							icon: 'error',
							title: '接口不存在，请检查请求地址是否正确！'
						});
						break;
					case 500:
						uni.showToast({
							icon: 'none',
							title: '遇到错误'
						});
						break;
					case 200:
						resolve(res);
						break;
					default:
						resolve(res);
						break;
				}
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					title: '请求失败，网络错误',
					icon: "none",
					duration: 1000
				})
				reject();
			},
		})
	})
}

/**
 * 文件上传
 * @param {Array|Object} filePath 图片数据
 * @returns {Promise<Array>}
 */
const upload = async (url = '', data = {}, imgurl = '') => {

	return new Promise(async (resolve, reject) => {
		uni.showLoading()
		uni.uploadFile({
			url: baseUrl + url,
			filePath: data.file,
			name: 'file',
			header: {
				'Authorization': 'Bearer ' + (uni.getStorageSync('token') || '')
			},
			formData: data,
			success: async (res) => {
				console.log(res)
				uni.hideLoading()
				let row = JSON.parse(res.data)
				switch (res.statusCode) {
					case 200:
						resolve(row);
						break;
					default:
						uni.showToast({
							icon: 'none',
							title: '遇到错误'
						});
						reject();
						break;
				}

			},
			fail: (err) => {
				uni.hideLoading()
				console.log('上传失败', err)
			},
		})
	})
}

module.exports = {
	get,
	post,
	put,
	del,
	ajax,
	upload,
};
